package com.waimai1.waimai.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.waimai1.waimai.common.BaseContext;
import com.waimai1.waimai.common.R;
import com.waimai1.waimai.common.Utils;
import com.waimai1.waimai.dto.LocalCouponDto;
import com.waimai1.waimai.dto.GetLocalGoodDto;
import com.waimai1.waimai.entity.*;
import com.waimai1.waimai.exception.EnumException;
import com.waimai1.waimai.exception.NotErrorException;
import com.waimai1.waimai.service.*;
import com.wechat.pay.java.service.cashcoupons.model.SendCouponResponse;
import com.wechat.pay.java.service.profitsharing.model.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;

@RestController
@RequestMapping("/localshop")
@Slf4j
public class LocalShopController {
    @Autowired
    private LocalShopService localShopService;
    @Autowired
    private ChoujiangService choujiangService;
    @Autowired
    private BranchShopService branchShopService;
    @Autowired
    private LocalGoodService localGoodService;
    @Autowired
    private MyOrderService orderService;
    @Autowired
    private TanchuangService tanchuangService;
    @Autowired
    private WepayService wepayService;
    @Autowired
    private LocalWepayService localWepayService;
    @Autowired
    private CouponPersonService couponPersonService;
    @Autowired
    private CouponService couponService;
    @Autowired
    private ChoujiangResService choujiangResService;
    @Autowired
    private ChoujiangWhiteService choujiangWhiteService;
    @Autowired
    private LocalCouponService localCouponService;
    @Autowired
    private LocalShoperService localShoperService;
    @Autowired
    private WepayOrderService wepayOrderService;
    @Autowired
    private UserService userService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private QuanyiPersonService quanyiPersonService;
    //    秒杀lua脚本 key1是保存秒杀数 ，argv1是库存数量，key2是保存购买人，argv2是购买人信息
    private static final String LUA_SCRIPT =
            "if tonumber(redis.call('exists',KEYS[1])) == 0 "
                    + "then redis.call('set',KEYS[1],ARGV[1]) end "
                    + "if tonumber(redis.call('exists',KEYS[2])) == 0 "
                    + "then redis.call('sadd',KEYS[2],'-1') end "
                    + "if tonumber(redis.call('get',KEYS[1]))>0 and tonumber(redis.call('sismember',KEYS[2],ARGV[2]))==0 then "
                    + "redis.call('incrby',KEYS[1],'-1') "
                    + "redis.call('sadd',KEYS[2],ARGV[2]) return 1 "
                    + "else return 0 end ";

    @PostMapping(value = "/upload", headers = "content-type=multipart/form-data")
    public R<String> upload(@RequestParam("file") MultipartFile file,
                            HttpServletRequest request) throws IOException {
        //文件为空返回
        if (file.isEmpty()) {
            throw new NotErrorException(EnumException.NULL_FILE);
        }
        //文件不为空判断是否是图片
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        //设置允许上传文件类型
        String suffixList = "jpg,png,ico,bmp,jpeg";
        if (!suffixList.contains(suffix)) {
            throw new NotErrorException(EnumException.NOT_IMAGE);
        }
        String filename1 = BaseContext.getAcid()+"-" + UUID.randomUUID() + file.getOriginalFilename();//生成唯一图片路径
        try {
            //使用绝对地址
            File filepath = new File("img");
            if (!filepath.exists()) {
                filepath.mkdirs();
            }
            Path parentPath = Paths.get(filepath.getCanonicalPath());
            // 文件保存路径
            Path fullPath = parentPath.resolve(filename1);
            // 转存文件
            file.transferTo(new File(fullPath.toString()));
            String url = filename1;
            return R.success(url);
        } catch (Exception e) {
            e.printStackTrace();
            throw new IOException();
        }
    }

    @PostMapping("/applyShop")
    public R<String> applyShop(@RequestBody LocalShop localShop) {
        LambdaQueryWrapper<LocalShop> shopLambdaQueryWrapper = new LambdaQueryWrapper<>();
        shopLambdaQueryWrapper.eq(LocalShop::getAddress, localShop.getAddress())
                .eq(LocalShop::getAcid,BaseContext.getAcid())
                .eq(LocalShop::getShopName, localShop.getShopName());
        if (null != localShopService.getOne(shopLambdaQueryWrapper, false)) {
            throw new NotErrorException(EnumException.SAME_SHOP);
        }
        LambdaQueryWrapper<LocalShop> shopLambdaQueryWrapper1 = new LambdaQueryWrapper<>();
        shopLambdaQueryWrapper1.eq(LocalShop::getAcid,BaseContext.getAcid())
                .eq(LocalShop::getOpenid, BaseContext.getopenId());
        if (null != localShopService.getOne(shopLambdaQueryWrapper1, false)) {
            throw new NotErrorException(EnumException.SAME_OPENID);
        }
        localShop.setAcid(BaseContext.getAcid());
        localShop.setStatus(Utils.SHOP_STATUS_APPLY);
        localShop.setOpenid(BaseContext.getopenId());
        localShop.setPass(DigestUtils.md5DigestAsHex(localShop.getPass().getBytes(StandardCharsets.UTF_8)));
        if (!localShopService.save(localShop)) {
            throw new NotErrorException(EnumException.NO_SAVE);
        }
        return R.success("ok");
    }

    @GetMapping("/getYouShop")
    public R<List<LocalShop>> getYouShop() {
        LambdaQueryWrapper<LocalShop> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LocalShop::getTag, "优")
                .eq(LocalShop::getAcid,BaseContext.getAcid())
                .eq(LocalShop::getStatus, "已通过")
                .orderByAsc(LocalShop::getNo);
        List<LocalShop> shops = localShopService.list(queryWrapper);
        //加上销量
        for (LocalShop shop : shops) {
            localShopService.addSoldCount(shop);
        }
        return R.success(shops);
    }

    @GetMapping("/getShopById/{id}")
    public R<LocalShop> getShopById(@PathVariable Integer id) {
        LocalShop res = localShopService.getById(id);
        if (null == res) {
            throw new NotErrorException(EnumException.NO_SHOP);
        }
        localShopService.addSoldCount(res);
        return R.success(res);
    }

    @PostMapping("/getSearchShop")
    public R<Map<String, Object>> getSearchShop(@RequestBody Map<String, Object> map) {
        LambdaQueryWrapper<LocalShop> queryWrapper = new LambdaQueryWrapper<>();
        String search = (String) map.get("search");
        String sort = (String) map.get("sort");
        String tag=(String)map.get("tag");
        queryWrapper.eq(LocalShop::getStatus, "已通过")
                .eq(LocalShop::getAcid,BaseContext.getAcid())
                .eq(!"默认行业".equals(sort), LocalShop::getSort, sort)
                .eq(StringUtils.isNotBlank(tag),LocalShop::getTag,tag)
                .orderByAsc(LocalShop::getNo)
                .like(null != search, LocalShop::getShopName, search);
        Page<LocalShop> page = new Page<>((Integer) map.get("page"), 1000);
        IPage<LocalShop> shopPage = localShopService.page(page, queryWrapper);
        List<LocalShop> shopList = shopPage.getRecords();
        //加上销量
        for (LocalShop shop : shopList) {
            localShopService.addSoldCount(shop);
        }
        Long total = shopPage.getTotal();
        Map<String, Object> res = new HashMap<>();
        res.put("shopList", shopList);
        res.put("total", total);
        return R.success(res);
    }

    @PostMapping("/getSearchGood")
    public R<Map<String, Object>> getSearchGood(@RequestBody Map<String, Object> map) {
        LambdaQueryWrapper<LocalGood> queryWrapper = new LambdaQueryWrapper<>();
        String searchName = (String) map.get("searchName");
//        queryWrapper.orderByAsc(LocalGood::getNo)
        queryWrapper.like(StringUtils.isNotEmpty(searchName), LocalGood::getGoodName, searchName)
                .eq(LocalGood::getAcid,BaseContext.getAcid());
        Page<LocalGood> page = new Page<>((Integer) map.get("page"), 10);
        IPage<LocalGood> goodPage = localGoodService.page(page, queryWrapper);
        List<LocalGood> goodList = goodPage.getRecords();
        Long total = goodPage.getTotal();
        Map<String, Object> res = new HashMap<>();
        res.put("goodList", goodList);
        res.put("total", total);
        return R.success(res);
    }

    //openid获取shop
    @GetMapping("/takeShop")
    public R<LocalShop> takeShop() {
        System.out.println(BaseContext.getopenId());
        LambdaQueryWrapper<LocalShop> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LocalShop::getOpenid, BaseContext.getopenId())
                .eq(LocalShop::getAcid,BaseContext.getAcid());
        LocalShop shop = localShopService.getOne(queryWrapper, false);
        return R.success(shop);
    }

    @PostMapping("/addGood")
    public R<String> addGood(@RequestBody LocalGood localGood) {
        localGood.setAcid(BaseContext.getAcid());
        if (!localGoodService.saveOrUpdate(localGood)) {
            throw new NotErrorException(EnumException.NO_SAVE);
        }
        return R.success("ok");
    }

    //    获取分店
    @GetMapping("/catchfendian/{sort}")
    public R<List<LocalShop>> getfendian(@PathVariable String sort) {
        if (sort.equals("dianzhang")) {
//            店长获取
            LambdaQueryWrapper<LocalShop> shopLambdaQueryWrapper = new LambdaQueryWrapper<>();
            shopLambdaQueryWrapper.eq(LocalShop::getOpenid, BaseContext.getopenId())
                    .eq(LocalShop::getAcid,BaseContext.getAcid());
            List<LocalShop> res = localShopService.list(shopLambdaQueryWrapper);
            return R.success(res);
        } else {
//            店员获取
            LambdaQueryWrapper<LocalShoper> shoperLambdaQueryWrapper = new LambdaQueryWrapper<>();
            shoperLambdaQueryWrapper.eq(LocalShoper::getOpenid, BaseContext.getopenId())
                    .eq(LocalShoper::getAcid,BaseContext.getAcid());
            List<LocalShoper> shopers=localShoperService.list(shoperLambdaQueryWrapper);
//            店员不存在
            if(shopers.size()==0){
                return R.success(null);
            }
//            店员存在
            List<Integer> shopIdList=new ArrayList<>();
            for(LocalShoper shoper : shopers){
                shopIdList.add(shoper.getShopId());
            }
            LambdaQueryWrapper<LocalShop> shopIdLamdaQuery=new LambdaQueryWrapper<>();
            shopIdLamdaQuery.in(LocalShop::getId,shopIdList);
            List<LocalShop> shops=localShopService.list(shopIdLamdaQuery);
            return R.success(shops);
        }
    }

    //    获取店长名下的所有店员
    @GetMapping("/catchshoper")
    public R<List<LocalShoper>> getshoper() {
//        获取店长名下的所有shopid
        LambdaQueryWrapper<LocalShop> shopLambdaQueryWrapper = new LambdaQueryWrapper<>();
        shopLambdaQueryWrapper.eq(LocalShop::getOpenid, BaseContext.getopenId())
                .eq(LocalShop::getAcid,BaseContext.getAcid());
        List<LocalShop> shops = localShopService.list(shopLambdaQueryWrapper);
        if (shops.size() == 0) {
            return null;
        }
        List<Integer> shopIdList = new ArrayList<>();
        for (LocalShop shop : shops) {
            shopIdList.add(shop.getId());
        }
//        获取shopid下的所有店员
        LambdaQueryWrapper<LocalShoper> shoperLambdaQueryWrapper = new LambdaQueryWrapper<>();
        shoperLambdaQueryWrapper.in(LocalShoper::getShopId, shopIdList)
                .eq(LocalShoper::getAcid,BaseContext.getAcid());
        List<LocalShoper> shopers = localShoperService.list(shoperLambdaQueryWrapper);
        return R.success(shopers);
    }

    //    获取openid的店员
    @GetMapping("/takeShoper/{shopId}")
    public R<LocalShoper> takeShoper(@PathVariable int shopId) {
        LambdaQueryWrapper<LocalShoper> shoperLambdaQueryWrapper = new LambdaQueryWrapper<>();
        shoperLambdaQueryWrapper.eq(LocalShoper::getOpenid, BaseContext.getopenId())
                .eq(LocalShoper::getShopId, shopId)
                .eq(LocalShoper::getAcid,BaseContext.getAcid());
        LocalShoper shoper = localShoperService.getOne(shoperLambdaQueryWrapper, false);
        return R.success(shoper);
    }

    //    申请店员
    @PostMapping("/applyShoper")
    public R<String> applyShoper(@RequestBody LocalShoper shoper) {
        LambdaQueryWrapper<LocalShoper> shoperLambdaQueryWrapper = new LambdaQueryWrapper<>();
        shoperLambdaQueryWrapper.eq(LocalShoper::getOpenid, BaseContext.getopenId())
                .eq(LocalShoper::getAcid,BaseContext.getAcid())
                .eq(LocalShoper::getShopId, shoper.getShopId());
//        申请过该店铺会员
        if (null != localShoperService.getOne(shoperLambdaQueryWrapper, false)) {
            throw new NotErrorException(1007, "已申请过该店铺");
        }
        shoper.setOpenid(BaseContext.getopenId());
        shoper.setAcid(BaseContext.getAcid());

        List<Integer> permissionList = new ArrayList<>();
        //默认添加核销功能
        permissionList.add(0);
        String permission = JSON.toJSONString(permissionList);
        shoper.setPermission(permission);
        shoper.setStatus("已申请");
        if (!localShoperService.save(shoper)) {
            throw new NotErrorException(1008, "保存申请失败");
        }
        return R.success("ok");
    }

    //    同意店员请求
    @GetMapping("/agreeShoper/{id}")
    public R<String> agreeShoper(@PathVariable Integer id) {
        LocalShoper shoper = new LocalShoper();
        shoper.setId(id);
        shoper.setStatus("启用");
        if (!localShoperService.updateById(shoper)) {
            throw new NotErrorException(1007, "更新失败");
        }
        ;
        return R.success("ok");
    }

    //    申请店员
    @PostMapping("/changePermission")
    public R<String> changePermission(@RequestBody LocalShoper shoper) {
        if (!localShoperService.updateById(shoper)) {
            throw new NotErrorException(1008, "更新失败");
        }
        return R.success("ok");
    }

    //    删除店员
    @GetMapping("/deleteShoper/{id}")
    public R<String> deleteShoper(@PathVariable Integer id) {
        if (!localShoperService.removeById(id)) {
            throw new NotErrorException(1007, "删除失败");
        }
        ;
        return R.success("ok");
    }

    //    通过shopid获取good
    @GetMapping("/getGoods/{id}")
    public R<List<LocalGood>> getGoods(@PathVariable Integer id) {
        LambdaQueryWrapper<LocalGood> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LocalGood::getShopId, id);
        queryWrapper.ne(LocalGood::getIsYuangong, 1)
                .eq(LocalGood::getAcid,BaseContext.getAcid());
        List<LocalGood> LocalGood = localGoodService.list(queryWrapper);
        return R.success(LocalGood);
    }
    //    通过shopid获取good
    @GetMapping("/getYuangongGoods")
    public R<Map<String,Object>> getYuangongGoods() {
        LambdaQueryWrapper<LocalGood> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LocalGood::getIsYuangong, 1);
        //获取到优惠商品

        List<LocalGood> localGoods = localGoodService.list(queryWrapper);
        List<Integer> shopIds=new ArrayList<>();
        //获取优惠商品的店铺
        for(LocalGood good :localGoods){
            if(!shopIds.contains(good.getShopId())){
                shopIds.add(good.getShopId());
            }
        }
        List<LocalShop> localShops=localShopService.listByIds(shopIds);
        //获取优惠买单的店铺
        LambdaQueryWrapper<LocalShop> maiQuery=new LambdaQueryWrapper<>();
        maiQuery.eq(LocalShop::getIsYuangong,1);
        List<LocalShop> maidanShops=localShopService.list(maiQuery);
        localShops.addAll(maidanShops);
        Map<String,Object> res=new HashMap<>();
        res.put("shops",localShops);
        res.put("goods",localGoods);
        return R.success(res);
    }
    @GetMapping("/getGoodById/{id}")
    public R<LocalGood> getGoodById(@PathVariable Integer id) {
        LocalGood res = localGoodService.getById(id);
        if (null == res) {
            throw new NotErrorException(EnumException.NO_GOOD);
        }
        return R.success(res);
    }

    @GetMapping("/delGood/{id}")
    public R<String> delGood(@PathVariable Integer id) {
        if (!localGoodService.removeById(id)) {
            throw new NotErrorException(EnumException.NO_DELETE);
        }
        return R.success("ok");
    }
//秒杀范例
//    @GetMapping("/getsk")
//    public Map getsecKill(String pid) {
//        Map resp = new HashMap();
//        String count = "10";
//        String uid = String.valueOf(new Random().nextInt(10000));
//        List keys = new ArrayList();
//        keys.add("P" + pid);
//        keys.add("U" + pid);
//        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>(LUA_SCRIPT, Long.class);
//        Long result = redisTemplate.execute(redisScript, keys, count, uid);
//        resp.put("uid", uid);
//        resp.put("result", result);
//        return resp;
//    }
    @PostMapping("/createLSOrder")
    public R<Object> createLSOrder(@RequestBody MyOrder localOrder) {
        if ("秒杀".equals(localOrder.getRemark())) {
            LocalGood good = localGoodService.getById(localOrder.getRestaurantId());
            if (null == good) {
                throw new NotErrorException(EnumException.NO_GOOD);
            }
            //            员工专属商品需要验证白名单
            if(good.getIsYuangong()==1){
                Boolean flag = redisTemplate.opsForSet().isMember(BaseContext.getAcid()+":yuangongWhite", BaseContext.getPhone());
                if(!flag){
                    throw new NotErrorException(1007,"没有购买资格");
                }
            }
//            getRestaurantId获取本地商品Id
            String StoreNum = String.valueOf(good.getStoreNum());
            List keys = new ArrayList();
            keys.add(BaseContext.getAcid()+":P" + localOrder.getRestaurantId());//记录数量
            keys.add(BaseContext.getAcid()+":U" + localOrder.getRestaurantId());//记录买家
            DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>(LUA_SCRIPT, Long.class);
            Long result = redisTemplate.execute(redisScript, keys, StoreNum, BaseContext.getopenId());
//          秒杀返回1表示通过可以购买
            if (result == 1) {
                //获取总价
                localOrder.setTotalPrice(orderService.getLocalPrice(localOrder.getComments()));
                localOrder.setStatus(Utils.STATUS_WAIT_PAY);
                localOrder.setOpenid(BaseContext.getopenId());
                localOrder.setAcid(BaseContext.getAcid());
                if (orderService.save(localOrder)) {
                    //添加延时关单功能
                    int delayTime = 5 * 60 * 1000;
                    redisTemplate.opsForZSet().add("cancelOrder", JSON.toJSONString(localOrder.getOutTradeNo()), System.currentTimeMillis() + delayTime);
                }
                good.setSoldNum(good.getSoldNum() + 1);
                localGoodService.updateById(good);
                redisTemplate.opsForHash().increment(BaseContext.getAcid()+":LSsoldCount", "shopId" + localOrder.getLocalShopId(), 1);
                return R.success("创建订单成功");
            } else {
                throw new NotErrorException(EnumException.NO_CREATE_ORDER);
            }
        }
        if ("优惠买单".equals(localOrder.getRemark())) {
            localOrder.setStatus(Utils.STATUS_WAIT_PAY);
            localOrder.setOpenid(BaseContext.getopenId());
            localOrder.setAcid(BaseContext.getAcid());

            if (!orderService.save(localOrder)) {
                throw new NotErrorException(EnumException.NO_CREATE_ORDER);
            }
            //添加延时关单功能
            int delayTime = 5 * 60 * 1000;
            redisTemplate.opsForZSet().add("cancelOrder", JSON.toJSONString(localOrder.getOutTradeNo()), System.currentTimeMillis() + delayTime);
            redisTemplate.opsForHash().increment(BaseContext.getAcid()+":LSsoldCount", "shopId" + localOrder.getLocalShopId(), 1);
            return R.success("创建订单成功");
        }
//        不是秒杀或买单
        //        获取总价
        localOrder.setTotalPrice(orderService.getLocalPrice(localOrder.getComments()));
        LocalGood good = localGoodService.getById(localOrder.getRestaurantId());
        if (null == good) {
            throw new NotErrorException(EnumException.NO_GOOD);
        }
        //创建订单和详情单
        localOrder.setStatus(Utils.STATUS_WAIT_PAY);
        localOrder.setOpenid(BaseContext.getopenId());
        localOrder.setAcid(BaseContext.getAcid());
        if (!orderService.save(localOrder)) {
            throw new NotErrorException(EnumException.NO_CREATE_ORDER);
        }
        //添加延时关单功能
        int delayTime = 5 * 60 * 1000;
        redisTemplate.opsForZSet().add("cancelOrder", JSON.toJSONString(localOrder.getOutTradeNo()), System.currentTimeMillis() + delayTime);
        good.setSoldNum(good.getSoldNum() + 1);
        if (!localGoodService.updateById(good)) {
            throw new NotErrorException(EnumException.NO_UPDATE);
        }
        redisTemplate.opsForHash().increment(BaseContext.getAcid()+":LSsoldCount", "shopId" + localOrder.getLocalShopId(), 1);
        return R.success("创建订单成功");
    }
    @PostMapping("/hexiaoOrder")
    public R<MyOrder> hexiaoOrder(@RequestBody Map<String, Object> map) {
        LambdaQueryWrapper<MyOrder> orderLambdaQueryWrapper = new LambdaQueryWrapper<>();
        orderLambdaQueryWrapper.eq(MyOrder::getQrCode, map.get("code"))
                .eq(MyOrder::getLocalShopId, map.get("shopId"))
//                .eq(MyOrder::getStatus, Utils.STATUS_PAYED)
                .eq(MyOrder::getAcid,BaseContext.getAcid());
        MyOrder order = orderService.getOne(orderLambdaQueryWrapper);
        if(null==order){
            throw new NotErrorException(1007,"核销码不存在");
        }else if(Utils.STATUS_OVER.equals(order.getStatus())){
            throw new NotErrorException(1008,"核销码已核销成功，请勿重复核销");
        }else if(Utils.STATUS_PAYED.equals(order.getStatus())) {
//            成功
            order.setStatus(Utils.STATUS_OVER);
        }else {
            throw new NotErrorException(EnumException.NO_HEXIAO);
        }
        if (!orderService.updateById(order)) {
            throw new NotErrorException(EnumException.NO_HEXIAO);
        }
        return R.success(order);
    }
//    核销社区团购订单
    @PostMapping("/hexiaoTuanOrder")
    @Transactional(rollbackFor = Exception.class)
    public R<MyOrder> hexiaoTuanOrder(@RequestBody Map<String, Object> map) {
        LambdaQueryWrapper<MyOrder> orderLambdaQueryWrapper = new LambdaQueryWrapper<>();
        orderLambdaQueryWrapper.eq(MyOrder::getQrCode, map.get("code"))
                .eq(MyOrder::getAcid,BaseContext.getAcid())
                .eq(MyOrder::getRemark,"社团")
                .eq(MyOrder::getTuanId, map.get("userId"));
        MyOrder order = orderService.getOne(orderLambdaQueryWrapper);
        if(null==order){
            throw new NotErrorException(1007,"核销码不存在");
        }else if(Utils.STATUS_OVER.equals(order.getStatus())){
            throw new NotErrorException(1008,"核销码已核销成功，请勿重复核销");
        }else if(Utils.STATUS_PAYED.equals(order.getStatus())) {
//            成功
            order.setStatus(Utils.STATUS_OVER);
        }else {
            throw new NotErrorException(EnumException.NO_HEXIAO);
        }
        if (!orderService.updateById(order)) {
            throw new NotErrorException(EnumException.NO_HEXIAO);
        }
        //对订单进行分账
        //获取wepay订单
        LambdaQueryWrapper<WepayOrder> wepayOrderLambdaQueryWrapper=new LambdaQueryWrapper<>();
        wepayOrderLambdaQueryWrapper.eq(WepayOrder::getOutTradeNo,order.getOutTradeNo());
        WepayOrder wepayOrder=wepayOrderService.getOne(wepayOrderLambdaQueryWrapper,false);
        if(null==wepayOrder){
            throw new NotErrorException(1009,"微信支付单不存在");
        }
        //获取团长openid
        User tuanzhang=userService.getById(order.getTuanId());
        if(null==tuanzhang){
            throw new NotErrorException(1010,"团长不存在");
        }
        localWepayService.addReceiver(wepayOrder.getSubMchid(), ReceiverType.PERSONAL_OPENID,tuanzhang.getOpenid(), ReceiverRelationType.DISTRIBUTOR);
        CreateOrderReceiver receiver=new CreateOrderReceiver();
        receiver.setType("PERSONAL_OPENID");
        receiver.setAccount(tuanzhang.getOpenid());
        receiver.setAmount(Math.round(wepayOrder.getTotal()*0.01));
        receiver.setDescription("描述");
        ArrayList< CreateOrderReceiver > receivers=new ArrayList<>();
        receivers.add(receiver);
        localWepayService.createFenzhang(wepayOrder.getSubMchid(),wepayOrder.getTransactionId(),"FZ"+order.getOutTradeNo(),receivers);
        return R.success(order);
    }
    //申请退款
    @GetMapping("/applyOrder/{outTradeNo}")
    public R<String> applyOrder(@PathVariable String outTradeNo) {
        LambdaQueryWrapper<MyOrder> orderLambdaQueryWrapper = new LambdaQueryWrapper<>();
        orderLambdaQueryWrapper.eq(MyOrder::getOutTradeNo, outTradeNo);
        MyOrder order = orderService.getOne(orderLambdaQueryWrapper, false);
        if (null == order || order.getStatus() != Utils.STATUS_PAYED) {
            throw new NotErrorException(EnumException.NO_REFUND_APPLY);
        }
        order.setStatus(Utils.STATUS_WAIT_REFUND);
        if (!orderService.updateById(order)) {
            throw new NotErrorException(EnumException.NO_REFUND_APPLY);
        }
        return R.success("ok");
    }

    public void sendCouponByNo(CouponPerson couponPerson) {
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.eq(User::getOpenid, BaseContext.getopenId())
                .eq(User::getAcid, BaseContext.getAcid());
        User user = userService.getOne(userLambdaQueryWrapper, false);
        LambdaQueryWrapper<com.waimai1.waimai.entity.Coupon> couponLambdaQueryWrapper = new LambdaQueryWrapper<>();
        couponLambdaQueryWrapper.eq(com.waimai1.waimai.entity.Coupon::getWexinNo, couponPerson.getWexinNo())
                .eq(Coupon::getStatus,"启用")
                .eq(Coupon::getAcid, BaseContext.getAcid());
        Coupon coupon = couponService.getOne(couponLambdaQueryWrapper, false);
        if(null==coupon){
            throw new NotErrorException(1007,"券不存在");
        }
        //        手机号没绑定
        if(StringUtils.isBlank(user.getPhone())){
            throw new NotErrorException(1203,"请先绑定手机号");
        }
//        发光了就不发了
        if (coupon.getSendCount() >= coupon.getCount()) {
            throw new NotErrorException(EnumException.NO_SEND_COUPON);
        }
//        如果白名单存在则判断是否在白名单中
        if(coupon.getWhite()==1){
            boolean inWhite = redisTemplate.opsForSet().isMember(BaseContext.getAcid()+":couponPersonWhite" + couponPerson.getWexinNo(), user.getPhone());
            if (!inWhite) {
                throw new NotErrorException(1204,"没有领取资格");
            }
        }
        SendCouponResponse res = wepayService.sendcoupon(couponPerson.getWexinNo(), BaseContext.getopenId());
        if (null == res.getCouponId()) {
            throw new NotErrorException(EnumException.NO_SEND_COUPON);
        }
        if (null != user && null != user.getPhone()) {
            couponPerson.setPhone(user.getPhone());
        }
        couponPerson.setCouponId(res.getCouponId());
        couponPerson.setOpenid((BaseContext.getopenId()));
        couponPerson.setStatus("已领取");
        couponPerson.setCreateTime(new Date());
        couponPerson.setGetTime(new Date());
        couponPerson.setAcid(BaseContext.getAcid());
        if (!couponPersonService.save(couponPerson)) {
            throw new NotErrorException(EnumException.NO_SAVE);
        }
        //coupon表领取数加一
        coupon.setSendCount(coupon.getSendCount() + 1);
        if (!couponService.updateById(coupon)) {
            throw new NotErrorException(EnumException.NO_UPDATE);
        }
    }

    //首页广告弹窗和抽奖领取代金券coupnonPerson中只有weino
    @PostMapping("sendCoupon")
    public R<String> sendCoupon(@RequestBody CouponPerson couponPerson) {
        this.sendCouponByNo(couponPerson);
        return R.success("ok");
    }
    //发放券包
    @PostMapping("sendCoupons")
    public R<String> sendCoupons(@RequestBody List<String> weinoList) {

        for(String weino:weinoList){
            CouponPerson couponPerson=new CouponPerson();
            couponPerson.setWexinNo(weino);
            //判断是否领取过
//            LambdaQueryWrapper<CouponPerson> couponPersonLambdaQueryWrapper=new LambdaQueryWrapper<>();
//            couponPersonLambdaQueryWrapper.eq(CouponPerson::getAcid,BaseContext.getAcid())
//                    .eq(CouponPerson::getOpenid,BaseContext.getopenId())
//            .eq(CouponPerson::getWexinNo,weino);
//            CouponPerson coupenPersonRes=couponPersonService.getOne(couponPersonLambdaQueryWrapper,false);
//            if(null!=coupenPersonRes){
//                throw new NotErrorException(1007,"请勿重复领取");
//            }
            this.sendCouponByNo(couponPerson);
        }
        return R.success("ok");
    }

    @GetMapping("/choujiangInit")
    public R<String> choujiangInit() {
        Choujiang choujiang = choujiangService.getCurrentChoujiang();
//        返回抽奖图片
        if (null == choujiang) {
            throw new NotErrorException(EnumException.NO_CHOUJIANG_CHOICE);
        }
        return R.success(choujiang.getImg());
    }

    @GetMapping("/choujiang")
    public R<Map> choujiang() {
        //判断抽奖机会
        Choujiang choujiang = choujiangService.getCurrentChoujiang();
        if (null == choujiang) {
            return R.err(1010, "当前无抽奖活动");
        }
//        1.获取用户信息
        User userRes = userService.getUserByOpenid();
        //2.判断积分要求
        if (choujiang.getCostPoint() > 0 && userRes.getUserPoint() < choujiang.getCostPoint()) {
            return R.err(1010, "积分不足");
        }
//        3.判断抽奖次数
        if (choujiang.getPersonCount() != 0) {
//            获取已抽奖次数
            int count = choujiangResService.getCount(choujiang.getId());
            if (count >= choujiang.getPersonCount()) {
                return R.err(1010, "抽奖次数已用完，请到奖品中心查看");
            }
        }
//        4.判断白名单
        if (choujiang.getUseWhite() == 1) {
            if (null == userRes.getPhone()) {
                throw new NotErrorException(EnumException.NO_CHOUJIANG_CHOICE);
            }
            boolean inWhite = redisTemplate.opsForSet().isMember(BaseContext.getAcid()+":choujiangWhite", userRes.getPhone());
            if (!inWhite) {
                return R.err(1010, "不在抽奖名单中");
            }
        }
//        5.判断完毕
        //计算角度和中奖结果
        String[] weight = choujiang.getWeight().split(",");
        String[] name = choujiang.getName().split(",");
        String[] weino = choujiang.getWeino().split(",");
        String[] count = choujiang.getCount().split(",");
        String[] sendCount = new String[count.length];
        if (null == choujiang.getSendCount()) {
            for (int i = 0; i < count.length; i++) {
                sendCount[i] = "0";
            }
        } else {
            sendCount = choujiang.getSendCount().split(",");
        }
        int nameIndex = 0;
        ArrayList<Double> qujian = new ArrayList<>();
        qujian.add(0.0);
        for (int i = 0; i < weight.length; i++) {
            //如果券发完了，则概率为0
            if (Integer.parseInt(count[i]) <= Integer.parseInt(sendCount[i])) {
                weight[i] = "0";
            }
            qujian.add(qujian.get(i) + Double.parseDouble(weight[i]));
        }
        int totalAng = 360 / choujiang.getXunhuan();
        int startAng = totalAng / weight.length / 2;
        double random = Math.random() * qujian.get(qujian.size() - 1);
        for (int j = 0; j < qujian.size(); j++) {
            if (random < qujian.get(j)) {
                startAng = startAng + totalAng * (j - 1) / weight.length;
                nameIndex = j - 1;
                break;
            }
        }
//        把发券总数加1
        sendCount[nameIndex] = String.valueOf(Integer.parseInt(sendCount[nameIndex]) + 1);
        StringJoiner sc = new StringJoiner(",");
        for (String i : sendCount) {
            sc.add(i);
        }
        //应加入事务
        choujiang.setSendCount(sc.toString());
        if (!choujiangService.updateById(choujiang)) {
            throw new NotErrorException(EnumException.NO_CHOUJIANG_CHOICE);
        }
//        积分减
        if (choujiang.getCostPoint() > 0) {
            userRes.setUserPoint(userRes.getUserPoint() - choujiang.getCostPoint());
            if (!userService.updateById(userRes)) {
                throw new NotErrorException(EnumException.NO_UPDATE);
            }
            ;
        }
//        choujiangres中记录
        ChoujiangRes choujiangRes = new ChoujiangRes();
        choujiangRes.setChoujiangId(choujiang.getId());
        choujiangRes.setJiangName(name[nameIndex]);
        choujiangRes.setOpenid(BaseContext.getopenId());
        choujiangRes.setPhone(userRes.getPhone());
        choujiangRes.setAcid(BaseContext.getAcid());
        if (!choujiangResService.save(choujiangRes)) {
            throw new NotErrorException(EnumException.NO_SAVE);
        }
        ;
        Map<String, Object> map = new HashMap<>();
        map.put("name", name[nameIndex]);
        map.put("ang", startAng);
        map.put("weino", weino[nameIndex]);
        return R.success(map);
    }

    @PostMapping("/takeChoujiangRes")
    public R<List> getChoujiangRes(@RequestBody Map<String, Object> map) {
        Integer pageId = (Integer) map.get("pageIndex");
        LambdaQueryWrapper<ChoujiangRes> resLambdaQueryWrapper = new LambdaQueryWrapper<>();
        resLambdaQueryWrapper.eq(ChoujiangRes::getOpenid, BaseContext.getopenId())
        .eq(ChoujiangRes::getAcid,BaseContext.getAcid());
        resLambdaQueryWrapper.orderByDesc(ChoujiangRes::getCreateTime);
        Page<ChoujiangRes> page = new Page<>(pageId, 10);
        IPage<ChoujiangRes> choujiangResPage = choujiangResService.page(page, resLambdaQueryWrapper);
        List<ChoujiangRes> choujiangResList = choujiangResPage.getRecords();
        return R.success(choujiangResList);
    }

//    @GetMapping("/getBranchShop/{id}")
//    public R<List<BranchShop>> getBranchShop(@PathVariable Integer id) {
//        LambdaQueryWrapper<BranchShop> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(BranchShop::getShopId, id);
//        List<BranchShop> BranchShops = branchShopService.list(queryWrapper);
//        return R.success(BranchShops);
//    }

    //判断openid是否有店铺
    @GetMapping("/haveShop")
    public R<Boolean> haveShop() {
        LambdaQueryWrapper<LocalShop> shopLambdaQueryWrapper = new LambdaQueryWrapper<>();
        shopLambdaQueryWrapper.eq(LocalShop::getOpenid, BaseContext.getopenId())
        .eq(LocalShop::getAcid,BaseContext.getAcid());
        if (null != localShopService.getOne(shopLambdaQueryWrapper, false)) {
            return R.success(true);
        } else {
            return R.success(false);
        }
    }

    //获取弹窗信息
    @GetMapping("/takeTanchuangUsing")
    public R<Tanchuang> takeTanchuangUsing() {
//        判断用户是否符合弹窗领券的条件
        LambdaQueryWrapper<Tanchuang> tanchuangLambdaQueryWrapper = new LambdaQueryWrapper<>();
        tanchuangLambdaQueryWrapper.eq(Tanchuang::getStatus, "正常")
        .eq(Tanchuang::getAcid,BaseContext.getAcid());
        Tanchuang tanchuang = tanchuangService.getOne(tanchuangLambdaQueryWrapper, false);
        if (null == tanchuang) {
            return null;
        }
        if (tanchuang.getSort().equals("代金券")) {
//            如果使用白名单
            if (tanchuang.getWhite() == 1) {
                if (StringUtils.isBlank(BaseContext.getPhone())) {
                    return null;
                }
                boolean inWhite = redisTemplate.opsForSet().isMember(BaseContext.getAcid()+":couponPersonWhite" + tanchuang.getWexinNo(), BaseContext.getPhone());
                if (!inWhite) {
                    return null;
                }
            }
            //如果领过也不能再领了
            LambdaQueryWrapper<CouponPerson> couponPersonLambdaQueryWrapper = new LambdaQueryWrapper<>();
            couponPersonLambdaQueryWrapper.eq(CouponPerson::getWexinNo, tanchuang.getWexinNo())
                    .eq(CouponPerson::getOpenid, BaseContext.getopenId())
                    .eq(CouponPerson::getAcid,BaseContext.getAcid());
            if (null != couponPersonService.getOne(couponPersonLambdaQueryWrapper, false)) {
                return null;
            }
            return R.success(tanchuang);
        } else if (tanchuang.getSort().equals("绑定手机号")) {
            if (StringUtils.isNotBlank(BaseContext.getPhone())) {
                return null;
            }
            return R.success(tanchuang);
        } else {
            return R.success(tanchuang);
        }

    }
    //用户查询可领券,同一时间，领取过一张券后，所有券都将不可领取
    @RequestMapping(value={"/yiwuCoupon"},method=RequestMethod.POST)
    public R<Map<String,Object>> yiwuCoupon(@RequestBody Map<String,Object> params){
        Map<String,Object> res=new HashMap<>();
        ArrayList<Coupon> coupons = new ArrayList<>();
        //未绑定手机号不可领券
        LambdaQueryWrapper<User> usrLambdaQueryWrapper=new LambdaQueryWrapper();
        usrLambdaQueryWrapper.eq(User::getOpenid,BaseContext.getopenId());
        User user=userService.getOne(usrLambdaQueryWrapper,false);
        if (StringUtils.isBlank(user.getPhone())) {
            res.put("couponList",coupons);
            return R.success(res);
        }
        String status=(String)params.get("status");
        Integer pageId=(Integer)params.get("pageIndex");
        Date now=new Date();
        //分页查出同一时间全部的可领取券
        LambdaQueryWrapper<Coupon> couponLambdaQueryWrapper=new LambdaQueryWrapper<>();
        couponLambdaQueryWrapper.eq(Coupon::getSort,"领券")
                .eq(Coupon::getAcid,BaseContext.getAcid())
                .eq(StringUtils.isNotBlank(status),Coupon::getStatus,status)
                .le(Coupon::getStartTime,now)
                .ge(Coupon::getCloseTime,now);
        Page<Coupon> page=new Page<>(pageId,10);
        IPage<Coupon> couponPage=couponService.page(page,couponLambdaQueryWrapper);
        List<Coupon> couponList=couponPage.getRecords();
        //获取全部的券的id列表
        ArrayList<String> weinoList=new ArrayList<>();
        for(Coupon coupon :couponList){
            weinoList.add(coupon.getWexinNo());
        }
        //查出当前用户领过的上述券的记录
        LambdaQueryWrapper<CouponPerson> couponPersonLambdaQueryWrapper=new LambdaQueryWrapper<>();
//        couponPersonLambdaQueryWrapper.eq(CouponPerson::getOpenid,BaseContext.getopenId())
        couponPersonLambdaQueryWrapper.eq(CouponPerson::getPhone,user.getPhone())
                .in(CouponPerson::getWexinNo,weinoList);
        CouponPerson couponPerson = couponPersonService.getOne(couponPersonLambdaQueryWrapper,false);
        //若已领取过券
        if(couponPerson!=null){
            for(Coupon coupon:couponList){
                if(coupon.getWexinNo().equals(couponPerson.getWexinNo())){
                    coupon.setStatus("已领取");
                }else{
                    coupon.setStatus("不可领取");
                }
                coupons.add(coupon);
                res.put("couponList",coupons);
            }
            return R.success(res);
        }
        //未领取过券
        for(Coupon coupon:couponList){
            if(coupon.getCount()<=coupon.getSendCount()){//券领光了显示领光
                coupon.setStatus("领完了");
            }else{
                coupon.setStatus("领取");
            }
            //若启用白名单
            if (coupon.getWhite() == 1) {
                boolean inWhite = redisTemplate.opsForSet().isMember(BaseContext.getAcid()+":couponPersonWhite"+coupon.getWexinNo(),user.getPhone());
                if (!inWhite) {//不在白名单
                    coupon.setStatus("未达标");
                }
            }
            coupons.add(coupon);
        }
        res.put("couponList",coupons);
        return R.success(res);
    }
//查询券列表
    @RequestMapping(value = {"/coupon"}, method = RequestMethod.POST)
    public R<Map<String, Object>> coupon(@RequestBody Map<String, Object> params) {
        String status = (String) params.get("status");
        Integer pageId = (Integer) params.get("pageIndex");
        Date now = new Date();
        LambdaQueryWrapper<Coupon> couponLambdaQueryWrapper = new LambdaQueryWrapper<>();
        couponLambdaQueryWrapper.eq(Coupon::getSort, "领券")
                .eq(Coupon::getAcid,BaseContext.getAcid())
                .eq(StringUtils.isNotBlank(status), Coupon::getStatus, status)
                .le(Coupon::getStartTime, now)
                .ge(Coupon::getCloseTime, now);
        Page<Coupon> page = new Page<>(pageId, 10);
        IPage<Coupon> couponPage = couponService.page(page, couponLambdaQueryWrapper);
        List<Coupon> couponList = couponPage.getRecords();
//        领取过的状态改成已领取
        ArrayList<String> weNoList = new ArrayList<>();
        for (Coupon coupon : couponList) {
            weNoList.add(coupon.getWexinNo());
        }
        LambdaQueryWrapper<CouponPerson> couponPersonLambdaQueryWrapper = new LambdaQueryWrapper<>();

        couponPersonLambdaQueryWrapper.eq(CouponPerson::getOpenid, BaseContext.getopenId())
                .eq(CouponPerson::getAcid,BaseContext.getAcid())
                .in(weNoList.size() != 0, CouponPerson::getWexinNo, weNoList);
        List<CouponPerson> couponPersons = couponPersonService.list(couponPersonLambdaQueryWrapper);
        List<Coupon> delCoupons = new ArrayList<>();
        List<String> couponPersonweino = new ArrayList<>();
        for (CouponPerson couponPerson : couponPersons) {
            couponPersonweino.add(couponPerson.getWexinNo());
//                if(coupon.getWexinNo().equals(couponPerson.getWexinNo())){
//                    coupon.setStatus("已领取");
//                    break;
//                }else{
//                    if(!coupon.getStatus().equals("领完了")){
//                        coupon.setStatus("领取");
//                    }
//                }
        }
        for (Coupon coupon : couponList) {
            //判断是否在白名单
            if (coupon.getWhite() == 1) {
                LambdaQueryWrapper<User> usrLambdaQueryWrapper = new LambdaQueryWrapper();
                usrLambdaQueryWrapper.eq(User::getOpenid, BaseContext.getopenId())
                        .eq(User::getAcid,BaseContext.getAcid());
                User user = userService.getOne(usrLambdaQueryWrapper, false);
                if (StringUtils.isBlank(user.getPhone())) {
                    delCoupons.add(coupon);
                    continue;
                }
                boolean inWhite = redisTemplate.opsForSet().isMember(BaseContext.getAcid()+":couponPersonWhite" + coupon.getWexinNo(), user.getPhone());
                if (!inWhite) {
                    delCoupons.add(coupon);
                    continue;
                }
            }
            log.info("领完了" + coupon.toString());
            if (couponPersonweino.contains(coupon.getWexinNo())) {
                coupon.setStatus("已领取");
            } else {
                coupon.setStatus("领取");
            }
            //券领光了显示领光
            if (coupon.getCount() <= coupon.getSendCount()) {
                coupon.setStatus("领完了");
            }
        }
        //删除不在白名单的数据
        if (delCoupons.size() != 0) {
            couponList.removeAll(delCoupons);
        }
        Map<String, Object> res = new HashMap<>();
        res.put("couponList", couponList);
        return R.success(res);
    }
    //创建本地商户优惠券
    @PostMapping("/createLocalCoupon")
    public R<String> createLocalCoupon(@RequestBody LocalCoupon localCoupon) {
        String couponNo = localCoupon.getShopId() + String.valueOf(new Date().getTime()).substring(9);
        localCoupon.setCouponNo(couponNo);
        localCoupon.setSendNumber(0);
        localCoupon.setAcid(BaseContext.getAcid());
        if (!localCouponService.save(localCoupon)) {
            throw new NotErrorException(EnumException.NO_SAVE);
        }
        return R.success("ok");
    }

    @GetMapping("/getLocalCoupon/{shopId}")
    public R<List<LocalCoupon>> getLocalCoupon(@PathVariable Integer shopId) {
        LambdaQueryWrapper<LocalCoupon> localCouponLambdaQueryWrapper = new LambdaQueryWrapper<>();
        localCouponLambdaQueryWrapper.eq(LocalCoupon::getShopId, shopId);
        return R.success(localCouponService.list(localCouponLambdaQueryWrapper));
    }

    @GetMapping("/getCouponByNo/{couponNo}")
    public R<LocalCoupon> getCouponByNo(@PathVariable Integer couponNo) {
        LambdaQueryWrapper<LocalCoupon> localCouponLambdaQueryWrapper = new LambdaQueryWrapper<>();
        localCouponLambdaQueryWrapper.eq(LocalCoupon::getCouponNo, couponNo)
        .eq(LocalCoupon::getAcid,BaseContext.getAcid());
        return R.success(localCouponService.getOne(localCouponLambdaQueryWrapper));
    }
    @GetMapping("/delLocalCoupon/{id}")
    public R<String> delLocalCoupon(@PathVariable Integer id) {
        if (!localCouponService.removeById(id)) {
            throw new NotErrorException(EnumException.NO_DELETE);
        }
        return R.success("ok");
    }
    //判断是否在白名单内，返回用户的星级给前端校验
    @GetMapping("/judgeInQuanyiWhite")
    public R<Integer> judgeInQuanyiWhite() {
        //从三个Redis的表里读当前用户id,累加三个表的用户
        int level = 0;
        level += Boolean.TRUE.equals(redisTemplate.opsForSet().isMember(BaseContext.getAcid()+":quanyiWhite" + "生日礼", BaseContext.getPhone())) ? 1 : 0;
        level += Boolean.TRUE.equals(redisTemplate.opsForSet().isMember(BaseContext.getAcid()+":quanyiWhite" + "中秋礼", BaseContext.getPhone())) ? 1 : 0;
        level += Boolean.TRUE.equals(redisTemplate.opsForSet().isMember(BaseContext.getAcid()+":quanyiWhite" + "过年礼", BaseContext.getPhone())) ? 1 : 0;
        //level= 2;
        return R.success(level);
    }

    //领取权益礼品并插入quanyi_person记录
    @PostMapping("/claimQuanyiGift")
    public R<String> claimQuanyiGift(@RequestBody JSONObject params) {
        String giftType = params.get("giftType").toString();
        log.info("giftType:{}", giftType);
        if (!Utils.giftTypeList.contains(giftType)) {
            return R.err(500, "礼物类型参数异常");
        }
        //后端校验当前用户是否能领取此类权益礼品
        int level = 0;
        level += Boolean.TRUE.equals(redisTemplate.opsForSet().isMember("quanyiWhite" + "生日礼", BaseContext.getPhone())) ? 1 : 0;
        level += Boolean.TRUE.equals(redisTemplate.opsForSet().isMember("quanyiWhite" + "中秋礼", BaseContext.getPhone())) ? 1 : 0;
        level += Boolean.TRUE.equals(redisTemplate.opsForSet().isMember("quanyiWhite" + "过年礼", BaseContext.getPhone())) ? 1 : 0;
        //level= 2;

        if ("生日礼".equals(giftType) && level < 1) {
            return R.success("用户星级需要四星级");
        } else if ("中秋礼".equals(giftType) && level < 2) {
            return R.success("用户星级需要五星级");
        } else if ("过年礼".equals(giftType) && level < 3) {
            return R.success("用户星级需要钻石级");
        }
        User user = userService.getUserByOpenid();
        QuanyiPerson quanyiPerson = new QuanyiPerson();
        quanyiPerson.setCreateTime(new Date());
        quanyiPerson.setName(user.getName());
        quanyiPerson.setPhone(user.getPhone());
        quanyiPerson.setOpenid(user.getOpenid());
        quanyiPerson.setSort(giftType);
        quanyiPerson.setAcid(BaseContext.getAcid());
        LambdaQueryWrapper<QuanyiPerson> quanyiPersonLambdaQueryWrapper = new LambdaQueryWrapper<>();
        quanyiPersonLambdaQueryWrapper.eq(QuanyiPerson::getOpenid, user.getOpenid())
                .eq(QuanyiPerson::getAcid,BaseContext.getAcid())
                .eq(QuanyiPerson::getSort, giftType);
        QuanyiPerson one = quanyiPersonService.getOne(quanyiPersonLambdaQueryWrapper);
        if (one != null) {
            return R.success("已领取过" + giftType);
        }
        quanyiPersonService.save(quanyiPerson);
        return R.success("领取成功");
    }
    //查看领取权益礼品状态
    @RequestMapping("/claimQuanyiGiftStatus")
    public R<HashMap<String, Boolean>> claimQuanyiGiftStatus() {
        LambdaQueryWrapper<QuanyiPerson> quanyiPersonLambdaQueryWrapper = new LambdaQueryWrapper<>();
        quanyiPersonLambdaQueryWrapper.eq(QuanyiPerson::getOpenid,BaseContext.getopenId());
        List<QuanyiPerson> list = quanyiPersonService.list(quanyiPersonLambdaQueryWrapper);
        HashMap<String, Boolean> map = new HashMap<>();
        list.stream().forEach((item)->{
            if("生日礼".equals(item.getSort())){
                map.put("shengri", true);
            }else if("中秋礼".equals(item.getSort())){
                map.put("zhongqiu", true);
            }else if("过年礼".equals(item.getSort())){
                map.put("guonian", true);
            }
        });
        return R.success(map);
    }
    //    商户，获取店长名下的所有店员并分页
    @PostMapping("/catchShoperByPage")
    public R<Map<String, Object>> catchShoperByPage(@RequestBody Map<String, Object> params) {
//        String wexinNo=(String)params.get("wexinNo");
        String name=(String)params.get("name");
        String status=(String)params.get("status");
        Integer pageIndex=(Integer)params.get("pageIndex");

        // 获取店长名下的所有shopid
        LambdaQueryWrapper<LocalShop> shopLambdaQueryWrapper=new LambdaQueryWrapper<>();
        shopLambdaQueryWrapper.eq(LocalShop::getOpenid,BaseContext.getopenId());
        List<LocalShop> shops=localShopService.list(shopLambdaQueryWrapper);
        if(shops.size()==0){
            return null;
        }
        List<Integer> shopIdList=new ArrayList<>();
        for(LocalShop shop:shops){
            shopIdList.add(shop.getId());
        }
        log.info("shopIdList:{}", shopIdList);
        //获取shopid下的所有店员
        LambdaQueryWrapper<LocalShoper> shoperLambdaQueryWrapper=new LambdaQueryWrapper<>();
        shoperLambdaQueryWrapper.in(LocalShoper::getShopId,shopIdList)
                .eq(StringUtils.isNotBlank(name),LocalShoper::getName,name)
                .eq(StringUtils.isNotBlank(status),LocalShoper::getStatus,status);
        Page<LocalShoper> page = new Page<>(pageIndex, 10);
        IPage<LocalShoper> shopersPage = localShoperService.page(page, shoperLambdaQueryWrapper);
        List<LocalShoper> shopers = shopersPage.getRecords();
        Long total = shopersPage.getTotal();
        Map<String, Object> res = new HashMap<>();
        res.put("shopers", shopers);
        res.put("total", total);
        return R.success(res);
    }
    //商户，更新店员信息
    @PostMapping("/updateShoperInfo")
    public R<String> updateShoperInfo(@RequestBody LocalShoper localShoper) {
        LocalShoper updateShoper = new LocalShoper();
        updateShoper.setStatus(localShoper.getStatus());
        updateShoper.setId(localShoper.getId());
        updateShoper.setName(localShoper.getName());
        updateShoper.setUpdateTime(new Date());
        updateShoper.setPermission(localShoper.getPermission());
        boolean flag = localShoperService.updateById(localShoper);
        if(flag){
            return R.success("更新店员信息成功");
        }
        throw new NotErrorException(1008,"更新店员信息失败");

    }
    //商户，获取当前登录商户所有店铺
    @PostMapping("/catchLocalShopList")
    public R<Map<String, Object>> catchLocalShopList(@RequestBody Map<String, Object> map) {
        LambdaQueryWrapper<LocalShop> queryWrapper = new LambdaQueryWrapper<>();
        String search = (String) map.get("search");
        String sort = (String) map.get("sort");
        String status = (String) map.get("status");
        queryWrapper.eq(LocalShop::getOpenid,BaseContext.getopenId())
                .eq(LocalShop::getAcid,BaseContext.getAcid())
                .eq(StringUtils.isNotEmpty(sort),LocalShop::getSort, sort)
                .eq(StringUtils.isNotEmpty(status),LocalShop::getStatus, status)
                .like(StringUtils.isNotEmpty(search), LocalShop::getShopName, search)
                .orderByAsc(LocalShop::getNo);
        Page<LocalShop> page = new Page<>((Integer) map.get("page"), 10);
        IPage<LocalShop> shopPage = localShopService.page(page, queryWrapper);
        List<LocalShop> shopList = shopPage.getRecords();
        Long total = shopPage.getTotal();
        Map<String, Object> res = new HashMap<>();
        res.put("shopList", shopList);
        res.put("total", total);
        return R.success(res);
    }
    //商户，更新店铺
    @PostMapping("/updateShop")
    public R<String> updateShop(@RequestBody LocalShop shop){
        if(StringUtils.isBlank(shop.getPass())) {
            shop.setPass(null);
        }else {
            shop.setPass(DigestUtils.md5DigestAsHex(shop.getPass().getBytes(StandardCharsets.UTF_8)));
        }
        boolean res=localShopService.updateById(shop);
        if(!res){
            throw new NotErrorException(EnumException.NO_UPDATE);
        }
        return R.success("ok");
    }
    //商户，添加分店
    @PostMapping("/addShop")
    public R<String> addShop(@RequestBody LocalShop localShop){
        LambdaQueryWrapper<LocalShop> shopLambdaQueryWrapper = new LambdaQueryWrapper<>();
        shopLambdaQueryWrapper.eq(LocalShop::getAddress, localShop.getAddress())
                .eq(LocalShop::getShopName, localShop.getShopName());
        if (null != localShopService.getOne(shopLambdaQueryWrapper, false)) {
            throw new NotErrorException(EnumException.SAME_SHOP);
        }
        localShop.setStatus(Utils.SHOP_STATUS_APPLY);
        localShop.setOpenid(BaseContext.getopenId());
        localShop.setAcid(BaseContext.getAcid());
//        localShop.setPass(DigestUtils.md5DigestAsHex(localShop.getPass().getBytes(StandardCharsets.UTF_8)));
        if (!localShopService.save(localShop)) {
            throw new NotErrorException(EnumException.NO_SAVE);
        }
        return R.success("ok");
    }
    //商户，获取当前商户所有商品
    @PostMapping("/catchGood")
    public R<Map<String, Object>> catchGood(@RequestBody GetLocalGoodDto getLocalGoodDto) {
        Date startTime=null,endTime=null;
        if(null!= getLocalGoodDto.getSelectTime()){
            startTime= getLocalGoodDto.getSelectTime()[0];
            endTime= getLocalGoodDto.getSelectTime()[1];
        }
        Integer pageIndex = getLocalGoodDto.getPageIndex();
        String goodName = getLocalGoodDto.getGoodName();
        Integer shopId = getLocalGoodDto.getShopId();

        List<Integer> shopIdList = null;
        if (null == shopId){
            // 获取店长名下的所有shopid
            LambdaQueryWrapper<LocalShop> shopLambdaQueryWrapper = new LambdaQueryWrapper<>();
            shopLambdaQueryWrapper.eq(LocalShop::getOpenid, BaseContext.getopenId())
            .eq(LocalShop::getAcid,BaseContext.getAcid());
            List<LocalShop> shops = localShopService.list(shopLambdaQueryWrapper);
            if (shops.size() == 0) {
                throw new RuntimeException("当前用户未绑定任何店铺");
            }
            shopIdList = new ArrayList<>();
            for (LocalShop shop : shops) {
                shopIdList.add(shop.getId());
            }
            log.info("shopIdList:{}", shopIdList);
        }
        LambdaQueryWrapper<LocalGood> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(null != shopId, LocalGood::getShopId, shopId)
                .in(null == shopId, LocalGood::getShopId, shopIdList)
                .like(StringUtils.isNotEmpty(goodName), LocalGood::getGoodName, goodName)
                .between(null != startTime&&null != endTime, LocalGood::getCreateTime, startTime, endTime)
                .orderByDesc(LocalGood::getCreateTime);
        Page<LocalGood> page = new Page<>(pageIndex, 10);
        IPage<LocalGood> goodPage = localGoodService.page(page, queryWrapper);
        List<LocalGood> goodList = goodPage.getRecords();
        Long total = goodPage.getTotal();
        Map<String, Object> res = new HashMap<>();
        res.put("goodList", goodList);
        res.put("total", total);
        return R.success(res);
    }

    //商户，获取当前登录商户店铺所有店铺id和名称
    @GetMapping("/catchShopName")
    public R<List<LocalShop>> catchShopName(){

        LambdaQueryWrapper<LocalShop> shopLambdaQueryWrapper = new LambdaQueryWrapper<>();
        shopLambdaQueryWrapper.select(LocalShop::getId,LocalShop::getShopName).eq(LocalShop::getOpenid, BaseContext.getopenId())
        .eq(LocalShop::getAcid,BaseContext.getAcid());
        List<LocalShop> shops = localShopService.list(shopLambdaQueryWrapper);
        if (shops.size() == 0) {
            throw new NotErrorException(EnumException.NO_SHOP);
        }
        return R.success(shops);
    }

    //商户,修改商品
    @PostMapping("/updateGood")
    public R<String> updateGood(@RequestBody LocalGood localGood) {

        boolean res=localGoodService.updateById(localGood);
        if(!res){
            throw new NotErrorException(EnumException.NO_UPDATE);
        }
        return R.success("ok");
    }

    //商户,修改本地券
    @PostMapping("/updateCoupon")
    public R<String> updateCoupon(@RequestBody LocalCoupon localCoupon) {

        boolean res=localCouponService.updateById(localCoupon);
        if(!res){
            throw new NotErrorException(EnumException.NO_UPDATE);
        }
        return R.success("ok");
    }
    //商户,创建优惠券
    @PostMapping("/createCouponBatch")
    public R<String> createCouponBatch(@RequestBody LocalCouponDto localCouponDto) {
        List<LocalCoupon> couponList = new ArrayList<>();
        localCouponDto.getShopIds().forEach((shopItemId)->{
            LocalCoupon localCoupon = new LocalCoupon();
            BeanUtils.copyProperties(localCouponDto,localCoupon);
            String couponNo = shopItemId + String.valueOf(new Date().getTime()).substring(9);
            localCoupon.setShopId(Integer.parseInt(shopItemId));
            localCoupon.setCouponNo(couponNo);
            localCoupon.setSendNumber(0);
            localCoupon.setAcid(BaseContext.getAcid());
            couponList.add(localCoupon);
        });
        if (!localCouponService.saveBatch(couponList)) {
            throw new NotErrorException(EnumException.NO_SAVE);
        }
        return R.success("ok");
    }

    //商户,查询旗下所有店铺优惠券
    @PostMapping("/findAllCoupon")
    public R<Map<String, Object>> findAllCoupon(@RequestBody LocalCouponDto localCouponDto) {
        Integer pageIndex = localCouponDto.getPageIndex();
        String couponName = localCouponDto.getName();
        List<String> shopIds = localCouponDto.getShopIds();
        String couponNo = localCouponDto.getCouponNo();
        LambdaQueryWrapper<LocalCoupon> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in( LocalCoupon::getShopId, shopIds)
                .eq(StringUtils.isNotBlank(couponNo),LocalCoupon::getCouponNo,couponNo)
                .like(StringUtils.isNotEmpty(couponName), LocalCoupon::getName, couponName)
//                .between(null != startTime&&null != endTime, LocalGood::getCreateTime, startTime, endTime)
                .orderByDesc(LocalCoupon::getId);
        Page<LocalCoupon> page = new Page<>(pageIndex, 10);
        IPage<LocalCoupon> couponPage = localCouponService.page(page, queryWrapper);
        List<LocalCoupon> couponList = couponPage.getRecords();
        Long total = couponPage.getTotal();
        Map<String, Object> res = new HashMap<>();
        res.put("couponList", couponList);
        res.put("total", total);
        return R.success(res);
    }
//    获取社区团购商品
@GetMapping("/getTuanGoods/")
public R<List<LocalGood>> getTuanGoods() {
    LambdaQueryWrapper<LocalGood> queryWrapper = new LambdaQueryWrapper<>();
    queryWrapper.eq(LocalGood::getSort, "社团")
            .eq(LocalGood::getAcid,BaseContext.getAcid());
    List<LocalGood> LocalGood = localGoodService.list(queryWrapper);
    return R.success(LocalGood);
}
}


